<template>
  <a-switch v-model:checked="isDarkMode" class="dark-switch" :loading="loading">
    <template #checkedChildren>
      <Icon type="icon-moon" />
    </template>
    <template #unCheckedChildren>
      <Icon type="icon-sun" />
    </template>
  </a-switch>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useHomeStore } from "/@/stores/home";
import { toggleDarkMode } from "/@/style/dark";
import { DARK_MODE_KEY, setItem, removeItem, getItem } from "/@/utils/storage";

const homeStore = useHomeStore();
const isDarkMode = ref(false);
const loading = ref(false);
watch(isDarkMode, async (v) => {
  loading.value = true;
  await toggleDarkMode(v);
  loading.value = false;
  homeStore.darkMode = v ? "dark" : "light";
  document.documentElement.classList[v ? "add" : "remove"]("dark");
  if (v) {
    setItem(DARK_MODE_KEY, "1");
  } else {
    removeItem(DARK_MODE_KEY);
  }
});
onMounted(() => {
  isDarkMode.value = !!getItem(DARK_MODE_KEY);
});
</script>
<style lang="less">
.dark-switch {
  border-width: 1px;
  border-color: transparent;
  border-style: solid;
  height: auto;
}
.dark {
  .dark-switch.ant-switch-checked {
    background-color: #1f1f1f;
    border-color: rgba(84, 84, 84, 0.65);
  }
  .dark-switch {
    .ant-switch-handle::before {
      background-color: #666666;
    }
  }
}
</style>
